import Vue from 'vue';
import Vuex from 'vuex';
import UserApi from '../api/user';
import SuggestionApi from '../api/suggestion';

Vue.use(Vuex);
const  state = {
  suggestionLoading: false,
  userInfo: {},
  isAuth: false,
  suggestionList: [],
  suggestionDetail: {}
}
const mutations = {
  setUserInfo: (state, info) => {
    console.log(info);
    state.userInfo = info;
  },
  setAuth: (state, status) => {
    state.isAuth = status;
  },
  setSuggestionLoading(state) {
    state.suggestionLoading = true;
  },
  setSuggestionLoaded(state) {
    state.suggestionLoading = false;
  },
  setSuggestionList(state, list) {
    state.suggestionList = list;
  },
  setSuggestionDetail(state, id) {
    const current = state.suggestionList.find(item => item.id == id);
    state.suggestionDetail = current;
  }
}
const actions = {
  // 授权
  async getSession (context, payload) {
    try {
      const res = await UserApi.getSession(payload);
      // context.commit('setUserInfo', res.data);
      mpvue.setStorageSync('token', res.data.token || '123');
      let pages = getCurrentPages();
      if (pages.length) {
        if (pages[pages.length - 1].route == 'pages/auth/index') {
          mpvue.reLaunch({
            url: '/pages/advise/index'
          });
        }
      }
    } catch (error) {
      if (error) {
        mpvue.showToast({
          title: '授权失败，请重试',
          icon: 'none'
        });
      }
      let pages = getCurrentPages();
      if (pages.length) {
        if (pages[pages.length - 1].route !== 'pages/auth/index') {
          mpvue.reLaunch({
            url: '/pages/auth/index'
          });
        }
      }
    }
  },

  // 获取建议列表
  async getSuggestionList(context, payload = {}) {
    try {
      const res = await SuggestionApi.list(payload.params);
      context.commit('setSuggestionList', res.data);
      if (payload.cb && typeof payload.cb == 'function') payload.cb();
    } catch (error) {
      if (error) {
        mpvue.showToast({
          title: error.message,
          icon: 'none'
        });
      }
    }
  },

  // 提交建议
  async submitSuggestion(context, payload = {}) {
    context.commit('setSuggestionLoading');
    try {
      await SuggestionApi.save(payload.params);
      if (payload.cb && typeof payload.cb == 'function') payload.cb();
      mpvue.showToast({
        title: '提交成功！',
        icon: 'success'
      });
    } catch (error) {
      if (error) {
        mpvue.showToast({
          title: error.message+'!',
          icon: 'none'
        });
      }
    }
    context.commit('setSuggestionLoaded');
  }
}
const store = new Vuex.Store({
  state,
  mutations,
  actions
});

export default store;
